package util

import (
	"encoding/base64"
	"fmt"
	"github.com/forgoer/openssl"
	"github.com/go-kratos/kratos/v2/log"
	"golang.org/x/crypto/bcrypt"
)

func HashPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10)
	return string(bytes), err
}

func CheckPasswordHash(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

// 加密
func AesEncrypt(data, aesKey string) string {
	dst, _ := openssl.AesECBEncrypt([]byte(data), []byte(aesKey), openssl.PKCS7_PADDING)
	return base64.StdEncoding.EncodeToString(dst)
}

// 解密
func AesDecrypt(data, aesKey string) string {
	defer func() {
		if err := recover(); err != nil {
			log.Info(fmt.Sprintf("%v", err))
		}
	}()
	baseDecrData, _ := base64.StdEncoding.DecodeString(data)
	dst, _ := openssl.AesECBDecrypt(baseDecrData, []byte(aesKey), openssl.PKCS7_PADDING)
	return string(dst)
}

// 手机号加密
func PhoneEncrypt(phone string) string {
	return AesEncrypt(phone, "E10ADC3949BA59ABBE56E057F20F883E")
}

// 手机号解密
func PhoneDecrypt(phoneCode string) string {
	return AesDecrypt(phoneCode, "E10ADC3949BA59ABBE56E057F20F883E")
}

// 手机号加密
func PhoneEncode(phone string) string {
	return phone[0:3] + "****" + phone[7:11]
}

// 手机号是否加密
func PhoneIsEncode(phone string) bool {
	return phone[3:7] == "****"
}
